package com.koutao.mall.config;

import com.koutao.mall.common.JacksonUtil;
import com.koutao.mall.common.ResultCode;
import com.koutao.mall.common.ResultData;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * Author:   koutao(301601)
 * Date:     2020/9/27 16:43
 * Description: TODO
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {

    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }


    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o == null) {
            // 结果为 null
            if (isJsonResponse(mediaType)){
                return new ResultData(ResultCode.OK);
            }else {
                return null;
            }
        } else {
            try {
                if (o instanceof ResultData) {
                    return o;
                } else if (o instanceof String ) {
                    return JacksonUtil.bean2Json(new ResultData<>(o));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return o;
    }


    private boolean isJsonResponse(MediaType mediaType) {
        switch (mediaType.toString()) {
            case MediaType.APPLICATION_JSON_VALUE :
            case MediaType.APPLICATION_JSON_UTF8_VALUE :
                return true;
            default:
                return false;
        }
    }

}
